<!-- 售后详情 -->
<template>
  <s-layout title="售后详情" :navbar="!isEmpty(state.info) && state.loading ? 'inner' : 'normal'">
    <view class="content_box" v-if="!isEmpty(state.info) && state.loading">
      <!-- 步骤条 -->
      <view
        class="steps-box ss-flex"
        :style="[
          {
            marginTop: '-' + Number(statusBarHeight + 88) + 'rpx',
            paddingTop: Number(statusBarHeight + 88) + 'rpx',
          },
        ]"
      >
        <!-- <uni-steps :options="state.list" :active="state.active" active-color="#fff" /> -->
        <view class="ss-flex">
          <view class="steps-item" v-for="(item, index) in state.list" :key="index">
            <view class="ss-flex">
              <text
                class="sicon-circleclose"
                v-if="
                  (state.list.length - 1 == index && state.info.aftersale_status === -2) ||
                  (state.list.length - 1 == index && state.info.aftersale_status === -1)
                "
              ></text>
              <text
                class="sicon-circlecheck"
                v-else
                :class="state.active >= index ? 'activity-color' : 'info-color'"
              ></text>

              <view
                v-if="state.list.length - 1 != index"
                class="line"
                :class="state.active >= index ? 'activity-bg' : 'info-bg'"
              ></view>
            </view>
            <view
              class="steps-item-title"
              :class="state.active >= index ? 'activity-color' : 'info-color'"
              >{{ item.title }}</view
            >
          </view>
        </view>
      </view>

      <!-- 服务状态 -->
      <view
        class="status-box ss-flex ss-col-center ss-row-between ss-m-x-20"
        @tap="sheep.$router.go('/pages/order/aftersale/log', { id: state.aftersaleId })"
      >
        <view class="">
          <view class="status-text">{{ state.info.aftersale_status_desc }}</view>
          <view v-if="state.info.refuse_reason && state.info.aftersale_status == -1" class="status-text">拒绝原因：{{ state.info.refuse_reason }}</view>
          <view class="status-time">{{ state.info.update_time }}</view>
        </view>
        <text class="ss-iconfont _icon-forward" style="color: #666"></text>
      </view>

      
      <!-- 商家已同意售后申请，请填写退货物流信息- 显示退货地址 -->
       <!-- have_refund_no：0=没填单号 1=已填单号 -->
      <view v-if="state.info.type == 'return' && state.info.is_agree == 1 && state.info.have_refund_no == 0 && state.info.aftersale_refund?.refund_phone" class="return-address ss-m-x-20 ss-m-t-20">
        <view class="top">
          <view class="title">退货地址</view>
          <button class="ss-reset-button copy-address-btn" hover-class="button-hover" @tap="onCopyAddress">复制地址</button>
        </view>
        <view class="content">
          <view class="content-item">
            <text>收&nbsp;&nbsp;货&nbsp;人：</text>
            <text class="value">{{ state.info.aftersale_refund?.refund_name }}</text>
          </view>
          <view class="content-item">
            <text>联系电话：</text>
            <text class="value">{{ state.info.aftersale_refund?.refund_phone }}</text>
          </view>
          <view class="content-item">
            <text>收货地址：</text>
            <text class="value">{{ state.info.aftersale_refund?.refund_province }} {{ state.info.aftersale_refund?.refund_city }} {{ state.info.aftersale_refund?.refund_county }} {{ state.info.aftersale_refund?.refund_address }}</text>
          </view>

          <view class="remark">温馨提示：不接收到付快递哦~</view>
        </view>
      </view>

      <!-- 填写物流单号之后，显示的物流信息 -->
      <!-- type="return" & is_agree=1 ===== 已经同意货款退款  -->
      <view v-if="state.info.type == 'return' && state.info.is_agree == 1 && state.info.have_refund_no == 1" class="writed-address ss-m-x-20 ss-m-t-20">
        <view class="top">
          <view class="title">退货物流信息</view>
          <view class="ss-reset-button copy-btn" @tap="viewLogisticsInfo">
            <text>查看</text>
            <text class="ss-iconfont _icon-forward" style="color: #999"></text>
          </view>
        </view>
        <view class="content">
          <view class="content-item">
            <text class="title">物流公司：</text>
            <text class="value">{{ state.info.aftersale_refund?.express_name }}</text>
          </view>
          <view class="content-item">
            <text class="title">物流单号：</text>
            <text class="value">{{ state.info.aftersale_refund?.express_number }}</text>
          </view>
          <view class="content-item">
            <text class="title">填写时间：</text>
            <text class="value">{{ state.info.aftersale_refund?.send_time }}</text>
          </view>
          <view class="content-item">
            <text class="title">退货说明：</text>
            <text class="value">{{ state.info.aftersale_refund?.express_info }}</text>
          </view>
          <view class="content-item" v-if="state.info.aftersale_refund?.voucher">
            <text class="title" style="opacity: 0;">退货图片：</text>
            <view class="value detail-img">
              <view class="img" v-for="img in imgArray" :key="img">
                <su-image
                  class="content-img"
                  isPreview
                  :previewList="state.refundImages"
                  :current="index"
                  :src="img"
                  :height="120"
                  :width="120"
                  mode="aspectFit"
                ></su-image>
              </view>
            </view>
          </view>
        </view>
      </view>

      <!-- 退款金额 -->
      <view class="aftersale-money ss-flex ss-col-center ss-row-between">
        <view class="aftersale-money--title">退款总额</view>
        <view class="aftersale-money--num">￥{{ state.info.refund_fee }}</view>
      </view>
      <!-- 服务商品 -->
      <view class="order-shop">
        <s-goods-item
          :title="state.info.goods_title"
          :price="state.info.goods_price"
          :img="state.info.goods_image"
          priceColor="#333333"
          :titleWidth="480"
          :skuText="state.info.goods_sku_text"
          :num="state.info.goods_num"
        ></s-goods-item>
      </view>

      <!-- 服务内容 -->
      <view class="aftersale-content">
        <view class="aftersale-item ss-flex ss-col-center">
          <view class="item-title">服务单号：</view>
          <view class="item-content ss-m-r-16">{{ state.info.aftersale_sn }}</view>
          <button class="ss-reset-button copy-btn" @tap="onCopy">复制</button>
        </view>
        <view class="aftersale-item ss-flex ss-col-center">
          <view class="item-title">申请时间：</view>
          <view class="item-content">{{ state.info.create_time }}</view>
        </view>
        <view class="aftersale-item ss-flex ss-col-center">
          <view class="item-title">售后类型：</view>
          <view class="item-content">{{ state.info.type_text }}</view>
        </view>
        <view class="aftersale-item ss-flex ss-col-center">
          <view class="item-title">申请原因：</view>
          <view class="item-content">{{ state.info.reason }}</view>
        </view>
        <view class="aftersale-item ss-flex ss-col-center">
          <view class="item-title">相关描述：</view>
          <view class="item-content">
            <view>{{ state.info.content }}</view>
            <view class="detail-img" v-if="state.info.images">
              <view class="img" v-for="img in state.info.images?.split(',')" :key="img">
                <su-image
                  class="content-img"
                  isPreview
                  :previewList="state.commentImages"
                  :current="index"
                  :src="img"
                  :height="120"
                  :width="120"
                  mode="aspectFit"
                ></su-image>
              </view>
            </view>
          </view>
        </view>
      </view>
    </view>
    <s-empty
      v-if="isEmpty(state.info) && state.loading"
      icon="/static/order-empty.png"
      text="暂无该订单售后详情"
    />
    <su-fixed bottom placeholder bg="bg-white" v-if="!isEmpty(state.info)">
      <view class="foot_box">
        <button
          class="ss-reset-button btn"
          v-if="state.info.btns?.includes('cancel')"
          @tap="onApply(state.info.id)"
          >取消申请</button
        >
        <!-- <button
          class="ss-reset-button btn"
          v-if="state.info.btns?.includes('delete')"
          @tap="onDelete(state.info.id)"
          >删除</button
        > -->
        <button class="ss-reset-button contcat-btn btn" @tap="sheep.$router.go('/pages/chat/index')"
          >联系客服</button
        >
        <button
          class="ss-reset-button btn btn-address"
          v-if="state.info.aftersale_status == -1"
          @tap="handleReApply"
          >重新申请</button
        >
        <button
          class="ss-reset-button btn btn-address"
          v-if="state.info.btns?.includes('submit_refund_express') && state.info.aftersale_refund?.refund_phone"
          @tap="handleReturnForm(state.info.id)"
          >填写退货物流</button
        >
      </view>
    </su-fixed>
  </s-layout>
</template>

<script setup>
  import sheep from '@/sheep';
  import { onLoad } from '@dcloudio/uni-app';
  import { reactive, computed } from 'vue';
  import { isEmpty } from 'lodash';

  const statusBarHeight = sheep.$platform.device.statusBarHeight * 2;
  const headerBg = sheep.$url.css('/static/img/shop/order/order_bg.png');
  const state = reactive({
    active: 0,
    aftersaleId: 0,
    info: {},
    list: [
      {
        title: '提交申请',
      },
      {
        title: '处理中',
      },
    ],
    loading: false,
    returnInfo: {
      nickname: '售后仓库',
      phone: '0571 6868 6333',
      address: '浙江省杭州市拱墅区萧山区北干街道区北干街道区北干街道',
    },
    commentImages: [],
    refundImages: []
  });

  const imgArray = computed(() => {
    if (state.info.aftersale_refund?.voucher) {
      let imgs = JSON.parse(state.info.aftersale_refund?.voucher)
      imgs = imgs.map(url => sheep.$url.cdn(url))
      state.commentImages = imgs
      return imgs
    } else {
      return []
    }
  })

  const onCopyAddress = () => {
    const { refund_province, refund_city, refund_county, refund_address, refund_phone, refund_name } = state.info.aftersale_refund;
    const addressText = `收货人：${refund_name || ''}\n联系电话：${refund_phone || ''}\n收货地址：${refund_province || ''} ${refund_city || ''} ${refund_county || ''} ${refund_address || ''}`;
    sheep.$helper.copyText(addressText);
  };

  const handleReturnForm = (id) => {
    console.log(id, 'id');
    sheep.$router.go('/pages/order/aftersale/returnForm', {item: JSON.stringify(state.info)});
  };

  // 重新申请
  const handleReApply = () => {
    const params = {...state.info, ...{ id: state.info.order_item_id }}
    console.log(params,'params')
    sheep.$router.go('/pages/order/aftersale/apply', {item: JSON.stringify(params)})
  }

  const viewLogisticsInfo = () => {
    console.log(state.info, 'state.info');
    sheep.$router.go('/pages/order/aftersale/logisticsInfo', {id: state.aftersaleId});
  };

  function onApply(orderId) {
    uni.showModal({
      title: '提示',
      content: '确定要取消此申请吗？',
      success: async function (res) {
        if (res.confirm) {
          const { error } = await sheep.$api.order.aftersale.cancel(orderId);
          if (error === 0) {
            getDetail(state.aftersaleId);
          }
        }
      },
    });
  }

  function onDelete(orderId) {
    uni.showModal({
      title: '提示',
      content: '确定要删除吗？',
      success: async function (res) {
        if (res.confirm) {
          const { error } = await sheep.$api.order.aftersale.delete(orderId);
          if (error === 0) {
            sheep.$router.back();
          }
        }
      },
    });
  }
  const onCopy = () => {
    sheep.$helper.copyText(state.info.aftersale_sn);
  };

  const handleImgs = data => {
    if (data.images) {
      console.log(data.images.split(','), '------')
      data.images.split(',').forEach((i) => {
        state.commentImages.push(sheep.$url.cdn(i));
        console.log(state.commentImages,'state.commentImages')
      });
    }
  }
  
  async function getDetail(id) {
    const { error, data } = await sheep.$api.order.aftersale.detail(id);
    state.loading = true;
    if (error === 0) {
      state.info = data;
      console.log(data,'data')

      console.log(state.info.aftersale_status,'state.info.aftersale_status')
      // 处理显示的图片
      handleImgs(state.info)
      //  COMMENT '售后状态:-2=已取消,-1=拒绝,0=未处理,1=申请售后,2=售后完成',
      if (state.info.aftersale_status === -2 || state.info.aftersale_status === -1) {
        console.log(1111)
        if (state.list.length == 3) { // 需要将完成状态去除，然后添加当前状态 - 取消/拒绝
          state.list.pop()
        }
        state.list.push({ title: state.info.aftersale_status_text });
        state.active = 2;
      } else {
        console.log(2222222)
        state.list.push({ title: '完成' });
        state.active = state.info.aftersale_status;
      }
    } else {
      state.info = null;
    }
  }
  onLoad((options) => {
    console.log(options,'optionsoptionsoptions')
    state.aftersaleId = options.id;
    getDetail(options.id);
  });
</script>

<style lang="scss" scoped>
  @import '../style/detail.scss';
  .steps-box {
    background: v-bind(headerBg) no-repeat,
      linear-gradient(90deg, var(--ui-BG-Main), var(--ui-BG-Main-gradient));
  }
</style>
